﻿using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Read.API.Command.MenuCommand;
using B.S.BaseData.Read.API.DTO;
using MediatR;

namespace B.S.BaseData.Read.API.CommandHandler.MenuHandler
{
    public class MenuQueryHandler : IRequestHandler<MenuQueryCommand, APIResult<APIPaging<MenuDTO>>>
    {
        private readonly IBaseRepository<MenuManagement> _menuRepository;

        public MenuQueryHandler(IBaseRepository<MenuManagement> menuRepository)
        {
            _menuRepository = menuRepository;
        }

        public async Task<APIResult<APIPaging<MenuDTO>>> Handle(MenuQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<MenuDTO>> result = new APIResult<APIPaging<MenuDTO>>();
            result.Code = APIEnum.Success;
            result.Msg = APIEnum.Success.ToString();

            var list = from a in _menuRepository.GetAll()
                       join b in _menuRepository.GetAll() on a.ParentId equals b.MenuId
                       where a.IsDeleted == false
                       select new MenuDTO
                       {
                           MenuId = a.MenuId,
                           MenuName = a.MenuName,
                           MenuUrl = a.MenuUrl,
                           ParentId = a.ParentId,
                           ParentMenuName = b.MenuName,
                           CreateTime = a.CreateTime,
                           CreateUser = a.CreateUser,
                           UpdateTime = a.UpdateTime,
                           UpdateUser = a.UpdateUser
                       };

            int TotalCount = list.Count();
            int TotalPage = (int) Math.Ceiling(TotalCount*1.0 / request.PageSize);
            list = list.OrderByDescending(p=>p.MenuId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            APIPaging<MenuDTO> paging = new APIPaging<MenuDTO>();
            paging.TotalCount = TotalCount;
            paging.PageCount = TotalPage;
            paging.Items = list.ToList();

            result.Data = paging;

            return await Task.FromResult(result);
        }
    }
}
